//
//  HMOAuthViewController.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMOauthViewController: UIViewController {

    // 懒加载 webView
    lazy var webView = UIWebView()
    
    // 将控制器的View设置为webView
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "新浪微博"
        
        setupNavigaitonBar()
        
        /// 获取oauth授权的登录界面地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = URL(string: urlString)
        
        // 加载授权登录界面
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        SVProgressHUD.show(withStatus: "正在加载登录界面...")
    }
    
    /// 设置导航栏
    private func setupNavigaitonBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.plain, target: self, action: #selector(autoFill))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(close))
        
        // title
        self.navigationItem.title = "登录"
    }
    
    // MARK: - 按钮点击事件
    func close() -> Void {
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充账号和密码
    @objc private func autoFill() {
        
        // document.getElementById('userId').value='czbkiosweibo@163.com'
        // document.getElementById('passwd').value='czbkios999'
        let jsCode = "document.getElementById('userId').value='czbkiosweibo@163.com';document.getElementById('passwd').value='czbkios111'"
        
        // 使用WebView执行JS代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}

extension HMOauthViewController: UIWebViewDelegate {
    // webView加载网页完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// webView是否加载某个URL,return true表示加载, return false不加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取webView要加载的地址
        let urlString = request.url!.absoluteString
        print("request = \(urlString)")
        
        // 如果加载的不是授权回调页面,直接加载网页,
        // 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消
        
        // 判断是否是回调地址
        if !urlString.hasPrefix(redirect_uri) {
            return true
        } else {
            
            print("回调地址: \(urlString)")
            
            // 判断后面是否跟有参数
            if let query = request.url!.query {
                let nsQuery = query as NSString
                let codeString = "code="
                // 判断query里面是否包含code=字符串
                if nsQuery.hasPrefix(codeString) {
                    let code = nsQuery.substring(from: codeString.characters.count)
                    print("拦截到code = \(code)")
                    
                    HMUserAccountViewModel.shared.loadAccessToken(code: code, completion: { (error: Error?) in
                        
                        if error != nil {
                            print("加载accessToken出错: \(error)")
                            SVProgressHUD.showError(withStatus: "您的网络不给力")
                            
                            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                                // 关闭授权控制器
                                self.close()
                            })
                            
                            return
                        }
                        
                        // 直接关闭控制器
                        print("加载accessToken完成")
                        self.close()
                        
                        AppDelegate.outSwitchRootViewController(controller: HMWelcomeViewController())
//                        let appDelegate = UIApplication.shared.delegate as! AppDelegate
//                        appDelegate.switchRootViewController(controller: HMWelcomeViewController())
                        
                    })
                } else {    //点击取消
                    close()
                }
            }
            
            return false
        }
    }
}
